import _createClass from "@babel/runtime/helpers/esm/createClass";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _assertThisInitialized from "@babel/runtime/helpers/esm/assertThisInitialized";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
import _wrapNativeSuper from "@babel/runtime/helpers/esm/wrapNativeSuper";

/**
 * 模板错误处理类
 * @param   {Object}    options
 */
var TemplateError = /*#__PURE__*/function (_Error) {
  _inherits(TemplateError, _Error);

  var _super = _createSuper(TemplateError);

  function TemplateError(options) {
    var _this;

    _classCallCheck(this, TemplateError);

    _this = _super.call(this, options.message);
    _this.name = 'TemplateError';
    _this.message = formatMessage(options);

    if (Error.captureStackTrace) {
      Error.captureStackTrace(_assertThisInitialized(_this), _this.constructor);
    }

    return _this;
  }

  return _createClass(TemplateError);
}( /*#__PURE__*/_wrapNativeSuper(Error));

function formatMessage(_ref) {
  var name = _ref.name,
      source = _ref.source,
      path = _ref.path,
      line = _ref.line,
      column = _ref.column,
      generated = _ref.generated,
      message = _ref.message;

  if (!source) {
    return message;
  }

  var lines = source.split(/\n/);
  var start = Math.max(line - 3, 0);
  var end = Math.min(lines.length, line + 3); // Error context

  var context = lines.slice(start, end).map(function (code, index) {
    var number = index + start + 1;
    var left = number === line ? ' >> ' : '    ';
    return "".concat(left).concat(number, "| ").concat(code);
  }).join('\n'); // Alter exception message

  return "".concat(path || 'anonymous', ":").concat(line, ":").concat(column, "\n\n        ").concat(context, "\n\n\n        ").concat(name, ": ").concat(message, "\n        ").concat(generated ? "\n   generated: ".concat(generated) : '');
}

export default TemplateError;